import { defineStore } from 'pinia'
import i18n from '~/i18n/index'
import ruRu from 'vant/es/locale/lang/ru-RU'
import zhCN from 'vant/es/locale/lang/zh-CN'
import { Locale } from 'vant'

export const useAppStore = defineStore('app', () => {
  const pending = ref(new Set<string>())
  const user = ref<UaaUserDetails>()
  const tgUser = ref<WebAppUser>()
  const token = ref<string>()
  const channelTip = ref<boolean>(false)

  const product = ref<ApiProductVO>()

  const drinks = ref<ApiOrderProductInfo[]>([])
  const products = ref<ApiOrderProductInfo[]>([])

  function delPending(id: string) {
    pending.value.delete(id)
  }

  function initOauth(auth: OAuthRes) {
    cache.setToken(auth.accessToken || '')
    cache.setTokenExpires(auth.expires || 0)
    cache.setRefreshToken(auth.refreshToken || '')
  }

  function initial(u: UaaUserDetails) {
    user.value = u
    token.value = u.token
  }

  const logined = computed(() => user.value != undefined)
  const loading = computed(() => pending.value.size > 0)

  function changeLang(lang: 'zhCn' | 'enUs' | 'ruRu') {
    i18n.global.locale.value = lang
    localStorage.setItem('localeLang', lang)
    setVantLang()
  }

  function setVantLang() {
    const lang = localStorage.getItem('localeLang') || 'ruRu'
    if (lang == 'ruRu') Locale.use('ru-RU', ruRu)
    if (lang == 'zhCn') Locale.use('zh-CN', zhCN)
  }

  return {
    pending,
    loading,
    user,
    tgUser,
    delPending,
    initOauth,
    initial,
    logined,
    changeLang,
    product,
    drinks,
    products,
    setVantLang,
    channelTip
  }
})
